from rest_framework import serializers
from .models import Host, DataCenter, City, HostStatistics

class CitySerializer(serializers.ModelSerializer):
    class Meta:
        model = City
        fields = ['id', 'name', 'created_at', 'updated_at']


class DataCenterSerializer(serializers.ModelSerializer):
    city = CitySerializer(read_only=True)
    city_id = serializers.PrimaryKeyRelatedField(queryset=City.objects.all(), source='city')

    class Meta:
        model = DataCenter
        fields = ['id', 'name', 'city', 'city_id', 'created_at', 'updated_at']


class HostSerializer(serializers.ModelSerializer):
    data_center = DataCenterSerializer(read_only=True)
    data_center_id = serializers.PrimaryKeyRelatedField(queryset=DataCenter.objects.all(), source='data_center')

    class Meta:
        model = Host
        fields = ['id', 'ip_address', 'hostname', 'data_center', 'data_center_id', 
                  'root_password', 'is_active', 'created_at', 'updated_at']
        extra_kwargs = {'root_password': {'write_only': True}}

    def create(self, validated_data):
        # 处理密码加密存储
        validated_data['root_password'] = make_password(validated_data['root_password'])
        return super().create(validated_data)

    def update(self, instance, validated_data):
        # 如果更新了密码，则加密存储
        if 'root_password' in validated_data:
            validated_data['root_password'] = make_password(validated_data['root_password'])
        return super().update(instance, validated_data)


class HostStatisticsSerializer(serializers.ModelSerializer):
    class Meta:
        model = HostStatistics
        fields = ['id', 'date', 'total_hosts', 'stats', 'created_at']
